package model

import (
	"crypto/rsa"
	"sort"
	"time"
	"wxpay/pkg/util"

	mchApi "wxpay/pkg/wechat_api"
)

/*
	平台证书
*/

type PlatformCert struct {
	SerialNo      string
	EffectiveTime time.Time
	ExpireTime    time.Time
	CertContent   string
}

type PlatformCerts []PlatformCert

func (certs PlatformCerts) GetPublicKey(serialNo string) (pubKey *rsa.PublicKey) {
	for i := range certs {
		if certs[i].SerialNo == serialNo {
			return mchApi.GetKeyFromCertificate(certs[i].CertContent)
		}
	}
	return nil
}

func (certs PlatformCerts) Len() int {
	return len(certs)
}

func (certs PlatformCerts) Less(i, j int) bool {
	// 倒序逻辑
	return certs[i].EffectiveTime.After(certs[i].EffectiveTime)
}

func (certs PlatformCerts) Swap(i, j int) {
	certs[i], certs[j] = certs[j], certs[i]
}

// 返回最新生效的证书
func (certs PlatformCerts) GetLatestCert() *PlatformCert {
	// 先排序（倒序）
	sort.Sort(certs)
	for i := range certs {
		if certs[i].EffectiveTime.Before(util.GetNow()) && certs[i].ExpireTime.After(util.GetNow()) {
			// 第一个生效的证书就是最新的
			return &certs[i]
		}
	}
	return nil
}
